<?php

/**
 * 每3分运行后台定时推送
 *
 * @author camfee<camfee@foxmail.com>
 */

require_once dirname(__DIR__) . "/cronBase.php";

use Common\Bridge;
use Mobile\AppPush;

class settimePush extends cronBase
{
    /**
     * 每3分定时运行的脚本
     */
    public function doDefault()
    {
        $select_date = date('Y-m-d H:i:s', time() + 600);
        $sql = 'SELECT `CronId`,`CronData`,`CronTime` FROM `AdminCron` WHERE `Type` = 1 AND `Status` = 0 AND `CronTime` <= "' . $select_date . '"';
        $data = $this->adminR($sql);
        if (!empty($data)) {
            foreach ($data as $v) {
                if ($v['CronTime'] <= date('Y-m-d H:i:s', time() + 180)) {
                    $cron_data = unserialize($v['CronData']);
                    if (!empty($cron_data['tag'])) { // 按用户类型推送
                        $result = AppPush::pushTag($cron_data['tag'], $cron_data['type'], $cron_data['msg'], $cron_data['data'], $cron_data['platform']);
                    } else { // 全体推送
                        $result = AppPush::pushAll($cron_data['type'], $cron_data['msg'], $cron_data['data'], $cron_data['platform']);
                    }
                    if ($result) {
                        $sql1 = 'UPDATE `AdminCron` set `Status`=1 WHERE `CronId`=' . $v['CronId'];
                        $this->adminW($sql1);
                    } else {
                        $sql2 = 'UPDATE `AdminCron` set `Status`=2 WHERE `CronId`=' . $v['CronId'];
                        $this->adminW($sql2);
                    }
                }
            }
        }
        exit('finished');
    }

    private $admin_w;

    /**
     * 写入数据库。
     *
     * @param $sql
     * @return array
     */
    private function adminW($sql)
    {
        if (empty($sql)) {
            echo 'SQL cannot empty';
            die;
        }
        if (!$this->admin_w) {
            $this->admin_w = Bridge::pdo(Bridge::DB_ADMIN_W);
        }
        $pdo = $this->admin_w;
        $result = $pdo->exec($sql);

        return $result;
    }

    private $admin_R;

    /**
     * Admin库的语句查询
     */
    private function adminR($sql)
    {
        if (empty($sql)) {
            echo 'SQL cannot empty';
            die;
        }
        if (!$this->admin_R) {
            $this->admin_R = Bridge::pdo(Bridge::DB_ADMIN_R);
        }
        $pdo = $this->admin_R;
        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }
}

$app->run();
